package com.fz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.fz.controller.request.BaseRequest;
import com.fz.exception.ServiceException;
import com.fz.mapper.BookMapper;
import com.fz.mapper.CategoryMapper;
import com.fz.pojo.Book;
import com.fz.service.BookService;
import com.fz.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<Book> list() {
        return bookMapper.list();
    }

    //分页
    @Override
    public PageInfo<Book> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Book> books = bookMapper.listByCondition(baseRequest);
        return new PageInfo<>(books);
    }

    //添加分类
    @Override
    public void addBook(Book book) {

        try {
            book.setCategory(category(book.getCategories()));
            bookMapper.addBook(book);
        }catch (Exception e){
            throw new ServiceException("数据插入错误",e);
        }



    }

    //通过id查询用户
    @Override
    public Book getById(Integer id) {
        return bookMapper.getById(id);


    }

    @Override
    public void update(Book book) {
        try {
            book.setCategory(category(book.getCategories()));
            book.setUpdateTime(new Date());
            bookMapper.updateById(book);
        }catch (Exception e){
            throw new ServiceException("数据更新错误",e);
        }



    }

    @Override
    public void deleteById(Integer id) {
        bookMapper.deleteById(id);
    }


    private  String category(List<String> categories){
        StringBuilder stringBuilder = new StringBuilder();
        if (CollUtil.isNotEmpty(categories)) {
            categories.forEach(v -> stringBuilder.append(v).append(">"));
            return stringBuilder.substring(0,stringBuilder.lastIndexOf(">"));
        }
        return stringBuilder.toString();
    }
}
